package com.example.exwebbrowser;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnKeyListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ImageButton;

public class BrowserActivity extends Activity implements OnKeyListener{

	private WebView webView;
	private ImageButton ibVoltar;
	private ImageButton ibInicio;
	private ImageButton ibIr;
	private EditText etURL;

	private final String URL_INICIAL = "http://www.google.com.br";
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //Carrega a interface que essa activity irá gerenciar
        setContentView(R.layout.main);
        //Setar Título da tela
        setTitle(getResources().getString(R.string.app_name));
        //Seta as variáveis de referencia a seus devidos componentes
        configComponentes();
    }

    //Seta as variáveis de referencia a seus devidos componentes e configurações
	@SuppressLint("SetJavaScriptEnabled")
	private void configComponentes() {
		ibVoltar = (ImageButton) findViewById(R.id.ibVoltar);
        ibInicio = (ImageButton) findViewById(R.id.ibInicio);
        ibIr = (ImageButton) findViewById(R.id.ibIr);
        etURL = (EditText) findViewById(R.id.etURL);
        webView = (WebView) findViewById(R.id.browser);
        //Instancia um novo cliente web para gerenciar nossa webView
		webView.setWebViewClient(new MyWebViewClient());
        //Ativar suporte a javaScript
        webView.getSettings().setJavaScriptEnabled(true);
        //Ativar suporte a zoom
        webView.getSettings().setSupportZoom(true);
	}
	 
    public void onClick(View v){
    	//botão voltar
    	if(v == ibVoltar){
    		if(webView.canGoBack()){
    			webView.goBack();
    		}
    	}
    	//botão home
    	if(v == ibInicio){
			webView.loadUrl(URL_INICIAL);
    	}
    	//botão ir
    	if(v == ibIr){
			webView.loadUrl(etURL.getText().toString());    		
    	}
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.maing, menu);
        return true;
    }

    //------------------ Métodos do Key Lsitener ------------------ 
      
	public boolean onKey(View v, int key, KeyEvent arg2) {
		if((v == etURL)&&(key == KeyEvent.KEYCODE_ENTER)){
			onClick(ibIr);
			etURL.setText(etURL.getText().toString());
			return true;
		}
		return false;
	}
	
	//Classe WebViewClient para gerenciar nossso Webview
	class MyWebViewClient extends WebViewClient{

		@Override
		public void onPageFinished(WebView view, String url) {
			etURL.setText(url);
			super.onPageFinished(view, url);
		}  
	}
	
}
